﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace ProjectManagement.TFS
{
    public class TfsSyncUtil
    {
        public static void SyncTwoServers(string srcTeamServer, string srcTeamProj, string tgtTeamServer, string tgtTeamProj)
        {
            TfsUtility tfsUtil=new TfsUtility();
            Workspace wkSpace1 = tfsUtil.GetCurrentWorkspace(srcTeamServer);
            Workspace wkSpace2 = tfsUtil.GetCurrentWorkspace(srcTeamServer);
            Debug.Assert(wkSpace1 != null, string.Format("Unable to map {0} to local machine", srcTeamServer));
            Debug.Assert(wkSpace2 != null, string.Format("Unable to map {0} to local machine", tgtTeamServer));
            Debug.Assert(wkSpace1.Computer == wkSpace2.Computer,
                         string.Format("Team project from server {0} and {1} must be mapped to local machine", srcTeamServer, tgtTeamServer));

            tfsUtil.CheckoutLatestVersion(srcTeamServer,srcTeamProj);
            tfsUtil.CheckoutLatestVersion(tgtTeamServer,tgtTeamProj);

            Dictionary<string, List<FileChangeHistory>> codeFiles1 = tfsUtil.GetAllFilesWithTeamProject(srcTeamServer, srcTeamProj,
                                                                                                        out wkSpace1);
            Dictionary<string, List<FileChangeHistory>> codeFiles2 = tfsUtil.GetAllFilesWithTeamProject(tgtTeamServer, tgtTeamProj,
                                                                                                        out wkSpace2);
            List<string> newFiles=new List<string>();
            List<string> changedFiles=new List<string>();
             
            foreach(string srcFilePath in codeFiles1.Keys)
            {
                List<FileChangeHistory> fileHistories = codeFiles1[srcFilePath];
                fileHistories.Sort();
                DateTime lastestModificationTime = fileHistories[0].TimeStamp;
                if(codeFiles2.ContainsKey(srcFilePath))
                {
                    List<FileChangeHistory> fileHistories2 = codeFiles2[srcFilePath];
                    fileHistories2.Sort();
                    DateTime latestModificationTime2 = fileHistories2[0].TimeStamp;
                    if(lastestModificationTime>latestModificationTime2)
                    {
                        changedFiles.Add(srcFilePath);
                    }
                }
                else
                {
                    newFiles.Add(srcFilePath);
                }
            }

        }
    }
}
